DB 연결 설정 분리
✒️ 2026-07-01 20:26 내용 수정
실습 참고 자료
- 인프런의 lettuce를 이용하여 redis 다루어 보기(저자: 신현호) 강의 내용을 참고하여 진행하였다.
중복 연결 설정 제거
- SpringBoot와 Redis 연결, TTL(Time To Live) 다루기, 숫자형 데이터 증감에서 여러 번 중복 작성 하던 Redis 연결 메서드를 인터페이스(interfaces)로 만들어 중복 코드를 제거한다.
package myproject.redis.lettuce;
import io.lettuce.core.api.sync.RedisCommands;
@FunctionalInterface
public interface CommandAction {
// Redis 명령 실행부
void doInExecute(RedisCommands<String, String> redisCommands);
}
package myproject.redis.lettuce;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
public class CommandTemplate {
public static void commandAction(CommandAction action) {
// Redis 클라이언트 생성
RedisClient redisClient = RedisClient.create(getRedisUri());
// Connection 연결
StatefulRedisConnection<String, String> connection = redisClient.connect();
// Redis 명령어
RedisCommands<String, String> redisCommands = connection.sync();
// 구현부
action.doInExecute(redisCommands);
connection.close();
redisClient.shutdown();
}
// Redis URI 생성
public static RedisURI getRedisUri() {
// host 주소
String host = "localhost";
return RedisURI.builder()
.withHost(host)
.withPort(6379) // 포트 번호. Docker에서 설정한 값과 동일하게 설정
.withDatabase(0) // 0 - 15까지 존재
.build();
}
}
- 기존 코드를 생성한 CommandTemplate과 CommandAction 인터페이스로 수정한다.
package io.github.crewhub.redis.lettuce.string;
import io.github.crewhub.redis.lettuce.CommandAction;
import io.github.crewhub.redis.lettuce.CommandTemplate;
import org.junit.jupiter.api.Test;
public class RedisLettuceStringRange {
@Test
public void incrDecr() {
CommandAction action = (redisCommands -> {
// Redis 연결 테스트를 위한 Key-value
String key = "lettuce:string";
String value = "hello";
redisCommands.set(key, value);
});
CommandTemplate.commandAction(action);
}
}
- Interface의 추상 메서드가 1개만 존재(
doInExecute)이므로 아래의 구현체를 람다 표현식으로 줄인 것과 동일하다.
CommandAction action = new CommandAction() {
@Override
public void doInExecute(RedisCommands<String, String> redisCommands) {
String key = "lettuce:string";
String value = "hello";
redisCommands.set(key, value);
}
};